package com.example.compose.retrofit.crash

import android.annotation.SuppressLint
import android.content.Intent
import com.example.compose.App
import com.example.compose.Constance
import com.example.compose.utils.LogUtil
import java.io.PrintWriter
import java.io.StringWriter
import java.io.Writer
import java.text.SimpleDateFormat
import java.util.*
import kotlin.system.exitProcess

object CrashHandler :Thread.UncaughtExceptionHandler {

    private lateinit var crash:Crash

    @JvmStatic
    fun initialization() {
        Thread.setDefaultUncaughtExceptionHandler(this)
        crash = Crash(
            Constance.AppInformation.appName(),
            Constance.AppInformation.packageName(),
            "Android",
            Constance.AppInformation.channel(),
            Constance.AppInformation.brand(),
            Constance.AppInformation.model(),
            Constance.AppInformation.release(),
            Constance.AppInformation.versionName(),
            Constance.AppInformation.versionCode(),
        )
        UploadLocalLogs().readLocalLogcat()
    }

    @SuppressLint("SimpleDateFormat")
    override fun uncaughtException(thread: Thread, throwable: Throwable) {
        val current = System.currentTimeMillis()
        val time: String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(current))
        crash.time = time
        crash.exceptionInfo = getExceptionInfo(throwable)
        LogUtil.i("上传日志 $crash")
        if(true/*BuildConfig.DEBUG*/){
            val intent = Intent(App().getContext(),LogcatActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.putExtra("crash", crash.exceptionInfo)
            intent.setClassName(App().getContext().packageName,LogcatActivity::class.java.name)
            App().getContext().startActivity(intent)
            exitProcess(0)
        }else{
            AddAppArashToRemotely().uploadCrashInfo(crash,thread,throwable)
        }
    }


    /**
     * 获取捕获异常的信息
     * @param ex
     */
    private fun getExceptionInfo(ex: Throwable): String {
        val writer: Writer = StringWriter()
        val printWriter = PrintWriter(writer)
        ex.printStackTrace(printWriter)
        ex.printStackTrace()
        var throwable = ex.cause
        while (throwable != null) {
            throwable.printStackTrace(printWriter)
            printWriter.append("\r\n")
            throwable = throwable.cause
        }
        printWriter.close()
        return writer.toString()
    }
}